import React, { Component } from 'react';
import { Table, Pagination, Message, Dialog, Button, Balloon } from '@alifd/next';
import IceContainer from '@icedesign/container';
import TableFilter from './TableFilter';
import SwitchNode from '../SwitchNode';
import axios from 'axios';
import moment from 'moment';
import SearchTableWrapper from '#/hoc/SearchTableWrapper'
import { ApiOfJobPage, ApiOfJobPause, ApiOfJobResume, ApiOfJobDelete, ApiOfJobRoutes } from '#/utils/coreApiDefine'

const responseFormatter = (responseHandler, res, originResponse) => {
  res = {
    success: res.status,
    message: '',
    data: {
      data: res.data.map(item => {
        return {
          jobGroup: item.jobDetail.jobGroup,
          jobKey: item.jobDetail.jobKey,
          jobName: item.jobDetail.jobName,
          description: item.jobDetail.description,
          startTime: moment(item.startTime).format('YY-MM-DD HH:mm:ss'),
          previousFireTime: moment(item.previousFireTime).format('YY-MM-DD HH:mm:ss'),
          nextFireTime: moment(item.nextFireTime).format('YY-MM-DD HH:mm:ss'),
          paused: item.jobDetail.paused,
          router: '',
        }
      }),
      pageable: res.pageable
    }
  };
  responseHandler(res, originResponse);
}

@SearchTableWrapper(ApiOfJobPage, { responseFormatter: responseFormatter })
export default class SearchTable extends Component {
  static displayName = 'SearchTable';

  static propTypes = {};

  static defaultProps = {
  };

  constructor() {
    super();
    this.state = {
      switchNodeDialogVisible: false,
      editInstance: {},
      routerInfoOfCurrentPageData: {},
    };
  }

  renderRouter = (value, index, item) => {
    let that = this;
    if (!this.state.routerInfoOfCurrentPageData[item.jobKey]) {
      return (
        <div></div>
      );
    } else {
      return (
        <div>
          <span>{that.state.routerInfoOfCurrentPageData[item.jobKey].currentNode}</span>
          <Button onClick={() => this.onOpenSwitchNodeDialog(that.state.routerInfoOfCurrentPageData[item.jobKey])} type="normal" size="small" style={{ marginLeft: '5px' }}>切换</Button>
        </div>
      );
    }
  }

  // 渲染操作按钮示例
  renderOper = (value, index, item) => {
    return (
      <div>
        <Button onClick={() => this.onChangeStatus(item)} type="primary" text>{item.paused ? '重启' : '暂停'}</Button>
        <span style={this.props.styles.separator} />
        <Button onClick={() => this.props.deleteConfirm(item, this.onDeleteConfirmOk.bind(this))} type="primary" text>删除</Button>
      </div>
    );
  }

  onChangeStatus = (item) => {
    let that = this;
    let Api = item.paused ? ApiOfJobResume : ApiOfJobPause
    Api(item.jobGroup, item.jobName).then(() => {
      that.setState({
        switchNodeDialogVisible: false
      });
      Message.success('操作成功!');
      that.props.fetch();
    })
  }

  onDeleteConfirmOk = (item) => {
    return ApiOfJobDelete(item.jobGroup, item.jobName);
  }

  onOpenSwitchNodeDialog = (router) => {
    this.setState({
      switchNodeDialogVisible: true,
      editInstance: router
    });
  }

  onCloseSwitchNodeDialog = reason => {
    this.setState({
      switchNodeDialogVisible: false
    });
    if (reason == 'success') {
      Message.success('操作成功!');
      this.props.fetch();
    }
  }

  render() {
    const { instances } = this.props.bindingData;
    return (
      <IceContainer style={this.props.styles.container}>
        <TableFilter
          filter={this.props.filter}
          match={this.props.match}
        />
        <Pagination
          style={{'marginBottom': '10px', ...this.props.styles.pagination}}
          shape="arrow-only"
          pageSizeSelector="filter"
          current={this.props.page}
          total={instances.pageable.totalElements}
          totalRender={total => `总数: ${total}`}
          pageSize={instances.pageable.size}
          onChange={this.props.handlePaginationChange}
          onPageSizeChange={this.props.handlePageSizeChange}
        />
        <Table
          dataSource={instances.data}
          loading={this.props.loading}
          hasBorder={false}
          style={{ padding: '0 20px 20px' }}
          onSort={this.props.handleSort}
        >
          <Table.Column width={280} title="任务组" dataIndex="jobKey" />
          <Table.Column title="任务描述" dataIndex="description" />
          <Table.Column width={130} title="开始时间" dataIndex="startTime" />
          <Table.Column width={130} title="上次触发时间" dataIndex="previousFireTime" />
          <Table.Column width={130} title="下次触发时间" dataIndex="nextFireTime" />
          <Table.Column
            width={240}
            title="路由信息"
            cell={this.renderRouter}
          />
          <Table.Column
            width={100}
            title="操作"
            cell={this.renderOper}
          />
        </Table>
        <Pagination
          style={this.props.styles.pagination}
          shape="arrow-only"
          pageSizeSelector="filter"
          current={this.props.page}
          total={instances.pageable.totalElements}
          totalRender={total => `总数: ${total}`}
          pageSize={instances.pageable.size}
          onChange={this.props.handlePaginationChange}
          onPageSizeChange={this.props.handlePageSizeChange}
        />
        <Dialog
          style={{ width: '50%' }}
          title="切换路由节点"
          visible={this.state.switchNodeDialogVisible}
          footer={false}
          onClose={this.onCloseSwitchNodeDialog}>
          <SwitchNode editInstance={this.state.editInstance} submitCallback={this.onCloseSwitchNodeDialog} />
        </Dialog>
      </IceContainer>
    );
  }

  shouldComponentUpdate(nextProps, nextState) {
    let that = this;
    if (nextProps.bindingData.instances != this.props.bindingData.instances) {
      let data = nextProps.bindingData.instances.data;
      axios
        .all(data.map(item => axios.get(ApiOfJobRoutes(item.jobGroup, item.jobName))))
        .then(axios.spread(function () {
          let routerInfoOfCurrentPageData = {}
          for (let i = 0; i < arguments.length; i++) {
            let response = arguments[i].data;
            if (!!response.data) {
              routerInfoOfCurrentPageData[response.data.jobKey] = response.data
            }
          }
          that.setState({ routerInfoOfCurrentPageData })
        }));
    }
    return true;
  }
}


